package approve.action;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import nguyen.dao.ReceiverDocumentDAO;
import project.active.L_list_subprolistmenu;
import project.active.ListProjectManager;
import project.active.LogoutActivity;
import project.active.Newproject;
import project.active.Projectlist;
import project.active.Projectlist_tc;
import model.pojo.Employee;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import approve.action.LoginActivity.PInfo;

public class MainFrame extends TabActivity {
	class PInfo {
		private String appname = "";
		private String pname = "";
		private String versionName = "";
		private int versionCode = 0;
	}
	
	static int soluong=0;
	TextView logout,username,report;
	String lang = "EN",database;
	Bundle language;
	Employee emp= new Employee();
	public String getDatabase() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			database = extras.getString("database");
		}
		return database;
	}
	ListView list;
	
	Timer timer=new Timer();
	NotificationManager mNotificationManager=null;
	private int SIMPLE_NOTFICATION_ID;

	L_list_subprolistmenu admenu;
	
	
	//auto update
	public int VersionCode;
	public String VersionName="";
	public String ApkName ;
	public String AppName ;
	public String BuildVersionPath="";
	public String urlpath ;
	public String PackageName;
	public String InstallAppPackageName;
	public String Text="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		language = getIntent().getExtras().getBundle(getLang());
		
		if(LoginActivity.flagupdateversion==false){
			Text= "New".toString();
			ApkName = "EliERP.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //      
			AppName="Eli ERP";
			BuildVersionPath = "http://14.63.215.15/EliERP/approval_version.txt".toString();
			PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
			urlpath = "http://14.63.215.15/EliERP/" + ApkName.toString();


			GetVersionFromServer(BuildVersionPath); 

			if(checkInstalledApp(AppName.toString()) == true)
			{   
				Toast.makeText(getApplicationContext(), language.getString("appfound")+" " + AppName.toString(), Toast.LENGTH_SHORT).show();
				System.out.println("login: true true");

			}else{
				Toast.makeText(getApplicationContext(),language.getString("appnotfound")+" "+ AppName.toString(), Toast.LENGTH_SHORT).show();          
				System.out.println("login: false false");
			}
			LoginActivity.flagupdateversion=true;
		}
		
		setContentView(R.layout.mainframe);
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
		emp=(Employee) getIntent().getExtras().get("em");
		showNotificationMessage();
		Resources res = getResources();
	    TabHost tabHost = getTabHost();
	    TabHost.TabSpec spec;
	    spec = tabHost.newTabSpec("approve").setIndicator(language.getString("ac_approved"),
	                      res.getDrawable(R.drawable.ic_tab_artists));
	    spec.setContent(new TabHost.TabContentFactory() {
			

			public View createTabContent(String tag) {
				// TODO Auto-generated method stub
				ListView listapprove = new ListView(MainFrame.this);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainFrame.this,android.R.layout.simple_list_item_1,listAllApprove(getLang()));
				listapprove.setAdapter(adapter); 
				listapprove.setOnCreateContextMenuListener(MainFrame.this);
				OnItemClickListener listener = new OnItemClickListener() {


					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						String item = arg0.getItemAtPosition(arg2).toString();
						if(item.equals("New Document") || item.equals("ë¬¸ì„œ ìž‘ì„±") ||item.equals("Táº¡o VÄƒn Báº£n")){
							Intent intent = new Intent(MainFrame.this,ApporoveNewActivity.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Pending Document")|| item.equals("ê²°ìž¬ëŒ€ê¸°ë¬¸ì„œ") ||item.equals("VÄƒn báº£n chá»� duyá»‡t")){
							Intent intent = new Intent(MainFrame.this,Re_PendingDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Not approved document")|| item.equals("ë¯¸ê²°ìž¬ë¬¸ì„œ ") ||item.equals("VÄƒn báº£n chÆ°a duyá»‡t")){
							Intent intent = new Intent(MainFrame.this,Re_NotApprovedDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
							
						}else if(item.equals("Approved document")|| item.equals("ê²°ìž¬ì™„ë£Œë¬¸ì„œ") ||item.equals("VÄƒn báº£n Ä‘Ã£ duyá»‡t")){
							Intent intent = new Intent(MainFrame.this,Re_ApprovedDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Decline document")|| item.equals("ë°˜ë ¤ë¬¸ì„œ") ||item.equals("VÄƒn báº£n bá»‹ tá»« chá»‘i")){
							Intent intent = new Intent(MainFrame.this,Re_DeclineDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Meeting document pending")|| item.equals("ë‚´ê°€ ë°›ì�€ íšŒì�˜ë¡�") ||item.equals("VÄƒn báº£n cuá»™c há»�p nháº­n")){
							Intent intent = new Intent(MainFrame.this,Re_MeetingDocumentPendding.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
//						}else if(item.equals("Meeting document sending")|| item.equals("ë‚´ê°€ ì˜¬ë¦° íšŒì�˜ë¡�") ||item.equals("VÄƒn báº£n cuá»™c há»�p gá»­i")){
//							
						}else if(item.equals("Reference document")|| item.equals("ì°¸ì¡°ë¬¸ì„œí•¨") ||item.equals("VÄƒn báº£n tham kháº£o")){
							Intent intent = new Intent(MainFrame.this,Re_ReferenceDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						
						/*Start MaiMai*/
						}else if(item.equals("My Document sending")|| item.equals("ìƒ�ì‹ ë¬¸ì„œi") ||item.equals("VÄƒn báº£n Ä‘Ã£ gá»Ÿi")){
							Intent intent = new Intent(MainFrame.this,My_App_DocumentSending.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);

						}else if(item.equals("My Saved document")|| item.equals("ìž„ì‹œë³´ê´€i") ||item.equals("VÄƒn báº£n lÆ°u")){
							Intent intent = new Intent(MainFrame.this,My_App_SavedDocument.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("My Approved document")|| item.equals("ê²°ìž¬ì™„ë£Œë¬¸ì„œi") ||item.equals("VÄƒn báº£n duyá»‡t")){
							Intent intent = new Intent(MainFrame.this,My_App_ApprovedDocument.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("My Decline document")|| item.equals("ë°˜ë ¤ë¬¸ì„œi") ||item.equals("VÄƒn báº£n tá»« chá»‘i")){
							Intent intent = new Intent(MainFrame.this,My_App_DeclineDocument.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("My Meeting document sending")|| item.equals("ë‚´ê°€ ì˜¬ë¦° íšŒì�˜ë¡�i") ||item.equals("VÄƒn báº£n há»�p gá»­i")){
							Intent intent = new Intent(MainFrame.this,My_App_MeetingDocumentSendding.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("Personal")|| item.equals("ê°œì�¸ê²°ìž¬ë�¼ì�¸") ||item.equals("CÃ¡ nhÃ¢n")){
							
						}
						/*End MaiMai*/
						else if(item.equals("Department")|| item.equals("ë¶€ì„œ") ||item.equals("PhÃ²ng Ban")){
							

							
						}else if(item.equals("Saved document")|| item.equals("ìž„ì‹œë³´ê´€") ||item.equals("VÄƒn báº£n Ä‘Æ°á»£c lÆ°u")){
							

						}
					}
					
				};
				listapprove.setOnItemClickListener(listener);
                 return listapprove;
			}
		});
	    tabHost.addTab(spec);

	    // Do the same for the other tabs
	    spec = tabHost.newTabSpec("project").setIndicator(language.getString("project"),
	                      res.getDrawable(R.drawable.ic_tab_artists));
	    spec.setContent(new TabHost.TabContentFactory() {
			

			public View createTabContent(String tag) {
				// TODO Auto-generated method stub
				ListView listproject = new ListView(MainFrame.this);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainFrame.this,android.R.layout.simple_list_item_1,listAllProject(getLang()));
				admenu = new L_list_subprolistmenu(MainFrame.this, listAllProject(getLang()));
//				listproject.setAdapter(adapter); 
				listproject.setAdapter(admenu); 
				
				
				listproject.setOnCreateContextMenuListener(MainFrame.this);
				OnItemClickListener listenerProject = new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						String item = arg0.getItemAtPosition(arg2).toString();
						if(emp.getIdrole()==1){
//							if(item.equals("ìƒˆ í”„ë¡œì �íŠ¸") || item.equals("Dá»± Ã¡n má»›i") || item.equals("New Project")){
//								Intent intent=new Intent(MainFrame.this,Newproject.class);
//								intent.putExtra("lang", getLang());
//								intent.putExtra("database", getDatabase());
//								intent.putExtra("em",emp);
//								//intent.putExtra("proaction", "newpro");
//								intent.putExtras(getIntent().getExtras());
//								startActivityForResult(intent, 0);
//							}else if(item.equals("List Project") || item.equals("í”„ë¡œì �íŠ¸ ë¦¬ìŠ¤íŠ¸") || item.equals("Danh sÃ¡ch dá»± Ã¡n")){
//								Intent intent=new Intent(MainFrame.this,Projectlist.class);
//								intent.putExtra("lang", getLang());
//								intent.putExtra("database", getDatabase());
//								intent.putExtra("em",emp);
//								intent.putExtras(getIntent().getExtras());
//								startActivityForResult(intent, 1);
//							}
							if(item.equals(language.getString("new_project"))){
								Intent intent=new Intent(MainFrame.this,Newproject.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								//intent.putExtra("proaction", "newpro");
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent, 0);
							}else if(item.equals(language.getString("ac_SUProjectList"))){
								Intent intent=new Intent(MainFrame.this,Projectlist.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent, 1);
							}
						}else{
							if(item.equals("List Manager") || item.equals("List mana") || item.equals("Du an quan ly")){
								Intent intent = new Intent(MainFrame.this,ListProjectManager.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent,0);
								
							}else if(item.equals("List Member") || item.equals("List mem") || item.equals("Du an thanh vien")){
								Intent intent=new Intent(MainFrame.this,Projectlist_tc.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent, 0);
							}
						}
						
					}
					
				};
				listproject.setOnItemClickListener(listenerProject );
                 return listproject;
			}
		});
	    tabHost.addTab(spec);
	    tabHost.setCurrentTab(2);
	    
	    Intent currentIntent = this.getIntent();
	    emp = (Employee)currentIntent.getSerializableExtra("em");
	    
//	    showDialogMessage();
	    logout=(TextView)findViewById(R.id.logout);
		username=(TextView)findViewById(R.id.username);
		logout.setText(language.getString("Logout"));
		
		logout.setOnClickListener(listenerLogout);
		username.setText(emp.getUserName());
//		report=(TextView)findViewById(R.id.report);
//		if(ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) == 0 || ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) == 1){
//			report.setText( "You have" + " " + ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) + " " + "new message");
//		}else{
//			report.setText( "You have" + " " + ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) + " " + "new messages");
//		}
	}
	
	private OnClickListener listenerLogout=new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
//			Intent i=new Intent(MainFrame.this, LoginActivity.class);	
			LoginActivity.flagupdateversion=false;
			soluong=0;
			timer.cancel();
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			
			Intent i=new Intent(MainFrame.this, LogoutActivity.class);
			i.putExtra("database", getDatabase());
			startActivity(i);
		}
	};

//	private void showDialogMessage(){
//		
//		int count=rd.countAllNewMessage(emp.getIdemployee(), getDatabase());
////		if(count==0 || count==1){
////			String message="You have "+count+" new message";
////			Button btt = new Button(this);
////			btt.setText("Submit");
////			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
////			
////			
////		}else{
////			String message="You have "+count+" new messages";
////			Button btt = new Button(this);
////			btt.setText("Submit");
////			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
////		}
////		
//		if(count <= 0){
//			Toast.makeText(this, "You hav'nt new message!", Toast.LENGTH_LONG).show();
//		}
//		else{
//			popupMessage(count);
//		}
//	}
	
//	private void popupMessage(int count){
//		AlertDialog.Builder popupmessage = new AlertDialog.Builder(this);
//		popupmessage.setTitle(count + " new message");
//		popupmessage.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//			
//			@Override
//			public void onClick(DialogInterface arg0, int arg1) {
//				final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://14.63.219.99/checkAndroidToPC.jsp?dbname="+getDatabase()+"&user="+emp.getUserName()+"&lg="+getLang()));
//				startActivity(intent);
//			}
//		});
//		popupmessage.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//			
//			@Override
//			public void onClick(DialogInterface arg0, int arg1) {
//				// TODO Auto-generated method stub
//				
//			}
//		});
//		// Remember, create doesn't show the dialog
//		AlertDialog messDialog = popupmessage.create();
//		messDialog.show();
//	}

	public String getLang() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			lang = extras.getString("lang");
		}
		return lang;
	}

	public String[] listAllApprove(String value) {
		String[] menu = null;
		if (value.equals("EN")) {
			menu = getResources().getStringArray(R.array.approval_en);
		} else if (value.equals("KR")) {
			menu = getResources().getStringArray(R.array.approval_kr);
		} else {
			menu = getResources().getStringArray(R.array.approval_vn);
		}
		return menu;
	}
	public String[] listAllProject(String value) {
		String[] menu = null;
		if(emp.getIdrole()==1){
//			if (value.equals("EN")) {
//				menu = getResources().getStringArray(R.array.project_en_admin);
//			} else if (value.equals("KR")) {
//				menu = getResources().getStringArray(R.array.project_kr_admin);
//			} else {
//				menu = getResources().getStringArray(R.array.project_vn_admin);
//			}
			menu= new String[2];
			if(language.getString("new_project")!=null){
				menu[0]=language.getString("new_project");
			}else
				menu[0]="";
			
			if(language.getString("ac_SUProjectList")!=null){
				menu[1]=language.getString("ac_SUProjectList");
			}else
				menu[1]="";
			
		}else{
			if (value.equals("EN")) {
				menu = getResources().getStringArray(R.array.project_en_member);
			} else if (value.equals("KR")) {
				menu = getResources().getStringArray(R.array.project_kr_member);
			} else {
				menu = getResources().getStringArray(R.array.project_vn_member);
			}
		}
		
		return menu;
	}
	
	private void showNotificationMessage(){
		timer.scheduleAtFixedRate(new mainTask(), 500, 50000);
	//	
	}
	ReceiverDocumentDAO rd = new ReceiverDocumentDAO();
	private class mainTask extends TimerTask {

		@Override
		public void run() {
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			final Notification notifyDetails;
			String idem = emp.getIdemployee();
			System.out.println("idem: "+idem);
			int count=rd.countAllNewMessage(idem, getDatabase());
			if(count>0){
				
//				if(count>0){
////					notifyDetails = new Notification(R.drawable.ic_launcher,
////						count + " new message", 500);
//					 notifyDetails = new Notification(R.drawable.ic_launcher,
//								count + " new message", System.currentTimeMillis());
//				}else if(count <=0){
////					notifyDetails = new Notification(R.drawable.ic_launcher,"",500);
//					notifyDetails = new Notification(R.drawable.ic_launcher,"",System.currentTimeMillis());
//					
//				}
//				else{
////					notifyDetails = new Notification(R.drawable.ic_launcher,
////							count + " new messages", 500);
//					notifyDetails = new Notification(R.drawable.ic_launcher,
//							count + " new messages", System.currentTimeMillis());
//				}
				
				if(count!=soluong){
					soluong=count;
//					notifyDetails = new Notification(R.drawable.ic_launcher,
//						count + " new message", 500);
					 notifyDetails = new Notification(R.drawable.ic_launcher,
								count + " new message", System.currentTimeMillis());
				
					 notifyDetails.defaults = Notification.DEFAULT_ALL;
						Context context = getApplicationContext();
						CharSequence contentTitle = "You have " + count + " new message";
						CharSequence contentText = "click me to view detail";
						

						Intent notifyIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://14.63.219.99/checkAndroidToPC.jsp?dbname="+getDatabase()+"&user="+emp.getUserName()+"&lg="+getLang()));
						
						PendingIntent intent = PendingIntent.getActivity(MainFrame.this,
								0, notifyIntent,
								android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

						notifyDetails.setLatestEventInfo(context, contentTitle,
								contentText, intent);
				//
						mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
								notifyDetails);
//						mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
//						
						
				}
			}
			 
		}
		
	}
	
	private Boolean checkInstalledApp(String appName){
		return getPackages(appName);    
	}
	
	// Get Information about Only Specific application which is Install on Device.
	public String getInstallPackageVersionInfo(String appName) 
	{
		String InstallVersion = "";     
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{
			//apps.get(i).prettyPrint();  
			
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
//				InstallVersion = "Install Version Code: "+ apps.get(i).versionCode+
//				" Version Name: "+ apps.get(i).versionName.toString();
				InstallVersion = apps.get(i).versionName.toString();
				break;
			}
		}
Toast.makeText(getApplicationContext(),language.getString("currenversion")+" : " + InstallVersion.toString(), Toast.LENGTH_LONG).show();
		
		return InstallVersion.toString();
	}
	private Boolean getPackages(String appName) 
	{
		Boolean isInstalled = false;
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		int max = apps.size();
		System.out.println(max);
		for (int i=0; i<max; i++) 
		{
			//apps.get(i).prettyPrint();
		
			System.out.println(apps.get(i).appname.toString() + " - " + appName.toString());
		
			
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				//System.out.println("b2");
				/*if(apps.get(i).versionName.toString().contains(VersionName.toString()) == true &&
                        VersionCode == apps.get(i).versionCode)
                {
                    isInstalled = true;
                    Toast.makeText(getApplicationContext(),
                            "Code Match", Toast.LENGTH_SHORT).show(); 
                    openMyDialog();
                }*/
				if(VersionCode <= apps.get(i).versionCode)
				{
					System.out.println("phien ban moi");
					isInstalled = false;

					/*Toast.makeText(getApplicationContext(),
                            "Install Code is Less.!", Toast.LENGTH_SHORT).show();*/

					/*DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:
								//Yes button clicked
								//SelfInstall01Activity.this.finish(); Close The App.

								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								//No button clicked

								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("New Apk Available..").setPositiveButton("Yes Proceed", dialogClickListener)
					.setNegativeButton("No.", dialogClickListener).show();*/

				}    
				if(VersionCode > apps.get(i).versionCode)
				{
					System.out.println("phien ban cu");
					isInstalled = true;
					/*Toast.makeText(getApplicationContext(),
                            "Install Code is better.!", Toast.LENGTH_SHORT).show();*/

					DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:
								//Yes button clicked
								//SelfInstall01Activity.this.finish(); Close The App.

								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								//No button clicked

								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage(language.getString("youareusingversion")+" "+getInstallPackageVersionInfo(AppName.toString()).toString()+". "+language.getString("nownewversion")
							+ GetVersionFromServer(VersionName.toString()).toString()+ ". "+language.getString("doyouwantinstall") +"?")
					.setPositiveButton(language.getString("install"), dialogClickListener)
					.setNegativeButton(language.getString("cancel"), dialogClickListener).show();              
//					builder.setMessage("chet may chua")
//					.setPositiveButton("install", dialogClickListener)
//					.setNegativeButton("cancel", dialogClickListener).show();  
				}
			}
		}

		
		
		
		return isInstalled;
	}
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) 
	{       
		ArrayList<PInfo> res = new ArrayList<PInfo>();        
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

		for(int i=0;i<packs.size();i++) 
		{
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue ;
			}
			if(p.applicationInfo.loadLabel(getPackageManager()).toString().equals(AppName)){
				PInfo newInfo = new PInfo();
				newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
				newInfo.pname = p.packageName;
				newInfo.versionName = p.versionName;
				newInfo.versionCode = p.versionCode;
				//newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
				///System.out.println(p.applicationInfo.loadLabel(getPackageManager()).toString()+"-"+p.packageName+"-"+p.versionName +" - "+ p.versionCode);
				res.add(newInfo);
			}
		}
		return res; 
	}


	public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
	{
		//Uri packageURI = Uri.parse("package:com.CheckInstallApp");
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent); 
	}
	public void InstallApplication()
	{   
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);

		//      Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

		//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//intent.setFlags(Intent.ACTION_PACKAGE_REPLACED);

		//intent.setAction(Settings. ACTION_APPLICATION_SETTINGS);

		intent.setDataAndType
		(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"  + ApkName.toString())), "application/vnd.android.package-archive");

		// Not open this Below Line Bcuz...
		////intent.setClass(this, Project02Activity.class); // This Line Call Activity Recursively its dangerous.

		startActivity(intent);  
	}
	public String GetVersionFromServer(String BuildVersionPath)
	{
		//this is the file you want to download from the remote server          
		//path ="http://10.0.2.2:82/Version.txt";
		//this is the name of the local file you will create
		// version.txt contain Version Code = 2; \n Version name = 2.1;             
		URL u;
		try {
			u = new URL(BuildVersionPath.toString());

			HttpURLConnection c = (HttpURLConnection) u.openConnection();           
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();

			//Toast.makeText(getApplicationContext(), "HttpURLConnection Complete.!", Toast.LENGTH_SHORT).show();  

			InputStream in = c.getInputStream();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..
			//in.read(buffer); //  Read from Buffer.
			//baos.write(buffer); // Write Into Buffer.

			int len1 = 0;
			while ( (len1 = in.read(buffer)) != -1 ) 
			{               
				baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
			}

			String temp = "";     
			String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;

			for (int i = 0; i < s.length(); i++)
			{               
				i = s.indexOf("=") + 1; 
				while (s.charAt(i) == ' ') // Skip Spaces
				{
					i++; // Move to Next.
				}
				while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
				{
					temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
					i++;
				}
				//
				s = s.substring(i); // Move to Next to Process.!
				temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
			}
			String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.

			VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
			VersionName = fields[1].toString();

			System.out.println("Vesiom code _ " + VersionCode);
			System.out.println("Vesion name _ " + VersionName);
			baos.close();
		}
		catch (MalformedURLException e) {
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (IOException e) {           
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
		return VersionName;
		//return true;
	}// Method End.

	// Download On My Mobile SDCard or Emulator.
	public void DownloadOnSDcard()
	{
		try{
			URL url = new URL(urlpath.toString()); // Your given URL.

			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect(); // Connection Complete here.!

			//Toast.makeText(getApplicationContext(), "HttpURLConnection complete.", Toast.LENGTH_SHORT).show();

			String PATH = Environment.getExternalStorageDirectory() + "/download/";
			File file = new File(PATH); // PATH = /mnt/sdcard/download/
			if (!file.exists()) {
				file.mkdirs();
			}
			File outputFile = new File(file, ApkName.toString());           
			FileOutputStream fos = new FileOutputStream(outputFile);

			//      Toast.makeText(getApplicationContext(), "SD Card Path: " + outputFile.toString(), Toast.LENGTH_SHORT).show();

			InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.

			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len1); // Write In FileOutputStream.
			}
			fos.close();
			is.close();
			System.out.println("thanh cong");
			//till here, it works fine - .apk is download to my sdcard in download file.
			// So plz Check in DDMS tab and Select your Emualtor.

			//Toast.makeText(getApplicationContext(), "Download Complete on SD Card.!", Toast.LENGTH_SHORT).show();
			//download the APK to sdcard then fire the Intent.
		} 
		catch (IOException e) 
		{
			System.out.println("that bai");
			System.out.println("Error! " +	e.toString());
			Toast.makeText(getApplicationContext(), "Error! " +	e.toString(), Toast.LENGTH_LONG).show();
		}           
	}
}
